package cn;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by wushifeng on 2017/3/14.
 */
public class DemoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    //重载doGet()方法
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        System.out.println(ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/"));

        String method = request.getParameter("method");
        response.setCharacterEncoding("UTF-8");
        Class clazz = this.getClass();
        if (StringUtils.isEmpty(method)) {
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.print("{\"code\":0,\"message\":\"\"}");
            return;
        }

        try {
            @SuppressWarnings("unchecked")
            Method m = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            if (m != null)
                m.invoke(this, request, response);
            else
                response.getOutputStream().print("no method");
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        }
    }
}